package com.luoyx.vjsb.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.luoyx.vjsb.authority.security.constant.SecurityConstant;
import com.luoyx.vjsb.authority.util.SecurityUtil;
import com.luoyx.vjsb.common.util.AjaxResult;
import com.luoyx.vjsb.common.util.AuthUtil;
import com.luoyx.vjsb.common.util.IpInfoUtil;
import com.luoyx.vjsb.core.entity.SysUser;
import com.luoyx.vjsb.core.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 登录
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/3/20 14:00
 */
@Api(tags = "登录")
@RestController
@RequestMapping("api")
public class LoginController {

    @Resource
    private SecurityUtil securityUtil;

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private IpInfoUtil ipInfoUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AuthUtil authUtil;

    @GetMapping("logout")
    @ApiOperation("系统退出")
    public AjaxResult<String> logout(HttpServletRequest request) {
        SysUser currUser = securityUtil.getCurrUser();
        currUser.setLastLoginTime(DateUtil.date())
            .setLastLoginIp(ipInfoUtil.getIpAddr(request));
        iSysUserService.updateById(currUser);
        // 清除缓存信息
        stringRedisTemplate.delete(SecurityConstant.USER_TOKEN + currUser.getUsername());
        stringRedisTemplate.delete(SecurityConstant.TOKEN_PRE + request.getHeader(SecurityConstant.HEADER));
        authUtil.removeToken();
        authUtil.removeUser();
        authUtil.removeUsername();
        return AjaxResult.success("成功退出");
    }
    @GetMapping(value = "/needLogin")
    @ApiOperation(value = "没有登录")
    public AjaxResult<String> needLogin(){
        return AjaxResult.error("您还未登录");
    }



    @PostMapping("images")
    @ApiOperation(value = "获取背景图")
    public AjaxResult<JSONObject> images(Integer n) {
        n = n == null ? 1 : n;
        String post = HttpUtil.post("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=" + n + "&mkt=zh-CN", "");
        return AjaxResult.success(JSONUtil.parseObj(post));
    }
}
